#include <iostream> //从A到C
using namespace std;
int n;
void ready() { cout << "请输入汉诺塔高度:"; cin >> n; cout << "默认从A移动到C" << endl; }
void move_recursion(int n, char des, char now, char temp) {
if (n == 1) { cout << 1 << "->" << des << endl; return; }
move_recursion(n - 1, temp, now, des);
cout << n << "->" << des << endl;
move_recursion(n - 1, des, temp, now);
}
void move_iterate(int n,char des, char now, char temp){
char inorder[2][4]={'0',temp,des,now,'0',des,now,temp};
int i,j,k;
char *np=new char[n+1];
for(int i=0;i<n+1;i++)np[i]='A';
for( i=1;i<(1<<n);i++){
for( j=i,k=1;j%2==0;k++,j/=2);
cout<<k<<" "<<np[k]<<"->";
np[k]=inorder[(1+n+k)%2][np[k]-'A'+1];
cout<<np[k]<<endl;}
}
int main(){
while (1) { ready(); move_iterate(n, 'C','A','B'); }
}
这上面的代码是我自己写的,迭代的过程参考了下面的代码,你们看不明白就不明白吧。
http://blog.csdn.net/silence_rui/article/details/19141519 直接模仿栈的迭代方法
#include <iostream> //从A到C
#include <stack>
struct Quad {
Quad();
Quad(int n, char a, char b, char c): _n(n), _x(a), _y(b), _z(c) {
}
int _n; // 要移动的盘子数量
char _x, _y, _z; // 保存柱子名称
}; // 保存当前状态
void hanoi(int, char, char, char);
int main(int argc, char *argv[])
{
hanoi(3, 'A', 'B', 'C');
return 0;
}
void hanoi(int n, char x, char y, char z)
{
std::stack<Quad> s;
s.push(Quad(n, x, y, z));
while (!s.empty()) {
Quad q = s.top();
s.pop();
n = q._n;
x = q._x;
y = q._y;
z = q._z;
if (n == 1) {
std::cout << "Move top disk from peg " << q._x
<< " to peg " << q._z << "\n";
}
else {
s.push(Quad(n - 1, y, x, z));
s.push(Quad(1, x, y, z));
s.push(Quad(n - 1, x, z, y));
}
}
}
http://blog.sina.com.cn/s/blog_48e3f9cd01000474.html 另一种迭代的方法
在版上看有人讨论汉诺塔的非